<?php

namespace App\Models;

use App\ModelFilters\Qh_QuestionLibraryFilter;
use DB;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Auth;

class Qh_QuestionLibrary extends BaseModel
{
    protected $table = 'qh_question_libraries';

    protected $guarded = [];

    protected $appends = ['userHas', 'userLearnQuestionCount'];

    public function modelFilter(): ?string
    {
        return $this->provideFilter(Qh_QuestionLibraryFilter::class);
    }

    public function course(): HasMany
    {
        return $this->hasMany(Qh_Course::class, 'qlId');
    }

    public function getUserHasAttribute(): bool
    {
        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();
            // 查询用户是否拥有了
            $userQuestionLibrary = DB::table('qh_user_has_question_libraries')->where('userId', $user->id)->where('qlId', $this->id)->first();
            if ($userQuestionLibrary) return true;
        }
        return false;
    }

    /**
     * 当前用户已学的试题数量
     * @return int
     */
    public function getUserLearnQuestionCountAttribute(): int
    {
        $count = 0;
        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();
            $count = DB::table('qh_user_learn')->where('qlId', $this->id)->where('userId', $user->id)->value('qCount') ?? 0;
        }
        return $count;
    }

    public function getComponentsAttribute($v) {
        if (request()->is('admin/*')) {
            if (is_null($v)) return [];
            // 排序
            $valueJson = json_decode($v);
            $componentsSorts = array();
            foreach ($valueJson as $key => $row) {
                $componentsSorts[$key] = $row->sort;
            }
            array_multisort($componentsSorts, SORT_ASC, $valueJson);
            return $valueJson;
        }
        else return $v;
    }
}
